/**
 * Created by huotaol on 2017/12/21.
 */
import React from 'react';
import { Button, Icon, Modal, Upload } from 'antd';
import { Feedback } from '@icedesign/base';
import request from '@/api/index.js';
import UUID from 'uuid-js';
import { connect } from 'react-redux';

const Toast = Feedback.toast;

class UploadPic extends React.Component {
  static defaultProps = {
    limit: 1,
    limitSize: 700 * 1024,
  };

  // 构造
  constructor(props) {
    super(props);
    // 初始状态
    this.state = {
      previewVisible: false,
      previewImage: '',
      uploading: false,
      fileList: this._valueToList(props.value),
    };
  }

  componentDidMount() {
  }

  componentWillReceiveProps(nextProps) {
    // 注意在上层 FormBinder 更新 value 之后，将组件内部 value 更新
    const value = nextProps.value;
    this.setState({
      fileList: this._valueToList(value),
    });
  }

  onChange = value => {
    if (this.props.onChange) {
      this.props.onChange(value);
    }
  };


  _valueToList = data => {
    if (Array.isArray(data)) {
      return data.map((v, index) => {
        return typeof v === 'string' ? { uid: -index, status: 'done', url: v } : v;
      });
    }
    return [];
  };

  _listToValue = list => {
    return list.map(v => {
      return v.static === 'done' ? v.url : v;
    });
  };

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  handleChange = ({ file, fileList }) => {
    const limitSize = this.props.limitSize;
    if (file.size > limitSize) {
      Toast.error(`不能超过${limitSize}`);
      return;
    }
    this._change(fileList);
  };

  /* 更新文件数组统一使用 */
  _change = fileList => {
    this.setState({ fileList });
    this.onChange(this._listToValue(fileList));
  };


  handleUpload = () => {
    const { fileList } = this.state;
    this.setState({
      uploading: true,
    });
    Promise.all(fileList.filter(f => f.status !== 'done')
      .map(m => this._uploadFile(m)))
      .then(() => {
        this.setState({ uploading: false });
      });
  };

  _uploadFile = file => {
    const uuid = UUID.create()
      .toString();
    request({ url: `/common/oss_auth/${uuid}`, method: 'get' })
      .then(rep => {
        const postfix = file.name.split('.')[1];
        const key = `${rep.dir}${uuid}.${postfix}`;
        const params = {
          key,
          policy: rep.policy,
          OSSAccessKeyId: rep.accessid,
          success_action_status: '200',
          signature: rep.signature,
          file: file.originFileObj,
        };
        request({ url: rep.host, method: 'post', params, skipCheckResp: true })
          .then(() => {
              const { fileList } = this.state;
              const newList = [];
              for (const t of fileList) {
                if (t.uid === file.uid) {
                  newList.push({ uid: t.uid, status: 'done', url: key });
                } else {
                  newList.push(t);
                }
              }
              this._change(newList);
            },
          );
      });
  };


  render() {
    const { previewVisible, previewImage, uploading } = this.state;
    const { profile } = this.props;
    const { basePicPrefix } = profile;
    const fileList = this.state.fileList.map(m => {
      if (m.status === 'done') {
        const reg = /^(http|https)/;
        const url = m.url;
        if (!reg.test(url)) {
          m.url = basePicPrefix + url;
        }
      }
      return m;
    });
    const { limit } = this.props;
    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text"/>
      </div>
    );
    return (
      <div>
        <Upload
          action="do not upload"
          listType="picture-card"
          fileList={fileList}
          disabled={fileList.length >= limit}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {uploadButton}
        </Upload>
        <Button
          className="upload-demo-start"
          type="primary"
          onClick={this.handleUpload}
          disabled={fileList.length === 0}
          loading={uploading}
        >
          {uploading ? '上传中...' : '开始上传'}
        </Button>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage}/>
        </Modal>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return { profile: state.profile };
};

export default connect(mapStateToProps)(UploadPic);

